package com.lifeonwalden.ms.web.msg.converter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

public class JsonConverter {
    public final static ObjectMapper defaultMapper = new ObjectMapper();

    static {
        SimpleModule module = new SimpleModule("DateFormat");
        module.addSerializer(Date.class, new StdSerializer<Date>(Date.class) {
            private static final long serialVersionUID = -3282010210198556897L;

            @Override
            public void serialize(Date value, JsonGenerator gen, SerializerProvider provider) throws IOException {
                gen.writeString(String.valueOf(value.getTime()));
            }
        });
        module.addSerializer(BigDecimal.class, new StdSerializer<BigDecimal>(BigDecimal.class) {
            private static final long serialVersionUID = -6469200275819994117L;

            @Override
            public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider) throws IOException {
                gen.writeString(value.toPlainString());
            }
        });
        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                return new Date(p.getLongValue());
            }
        });
        module.addDeserializer(BigDecimal.class, new JsonDeserializer<BigDecimal>() {
            @Override
            public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                return new BigDecimal(p.getValueAsString());
            }
        });
        defaultMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        defaultMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        defaultMapper.registerModule(module);
    }
}
